/*******************************************************************************
 *
 * File Name:          LoginAction.java
 *
 * Created:            2006-9-30 13:15:11
 *
 * Original Author:    yu.peng
 *
 *------------------------------------------------------------------------------
 * MODIFICATION HISTORY
 *------------------------------------------------------------------------------
 * WHEN                WHO                 WHY
 * 2006-9-30 13:15:11 yu.peng             new
 *------------------------------------------------------------------------------
 *
 ******************************************************************************/
/*******************/
/* PACKAGE SECTION */
/*******************/
package org.njo.webapp.root.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.validator.GenericValidator;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.njo.webapp.root.model.RemoteUser;
import org.njo.webapp.root.model.activity.Authenticate;
import org.njo.webapp.root.servlet.wrapper.RemoteUserRequestWrapper;
import org.njo.webapp.root.utility.AuthenticateException;
import org.njo.webapp.root.utility.ObjectNotExistsException;

/**
 * Login处理.
 *
 * 注意:
 * 1,这个Action只在Login成功的情况下跳转,
 *   失败时不需要跳转,因为在Login处理后,
 *   会再次请求上次请求的页面,如果Login后
 *   仍然没有合法的角色,会通过RequestProcessor
 *   再次跳转到Login页面.
 *
 * TODO:错误消息,错误消息的输出方式,日后需要重新定义.
 * Message
 *     target  发生错误元,null时代表整体错误
 *     key     错误消息的key.用于国际化时,错误消息的key
 *     message 根据key取得的消息.
 *  Messages 作为错误消息的集合
 * 
 * @author yu.peng
 * @version 0.01
 */
public class LoginAction extends Action {

    // --------------------------------------------------------- Public Methods
    /**
     * Process the specified HTTP request, and create the corresponding HTTP
     * response (or forward to another web component that will create it).
     * Return an <code>ActionForward</code> instance describing where and how
     * control should be forwarded, or <code>null</code> if the response has
     * already been completed.
     *
     * @param mapping  The ActionMapping used to select this instance
     * @param form     The optional ActionForm bean for this request (if any)
     * @param request  The HTTP request we are processing
     * @param response The HTTP response we are creating
     * @throws Exception if the application business logic throws
     *                   an exception
     */
    public ActionForward execute(ActionMapping mapping,
                                 ActionForm form,
                                 HttpServletRequest request,
                                 HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        RemoteUser remoteUser = null;

        //用户在Login界面输入用户名和密码
        String username = request.getParameter("name");
        String password = request.getParameter("password");
        String redirect = request.getParameter("redirect");

        // 校验输入
        if (!validate(request)) {
            return (new ActionForward(RequestProcessor.DEFAULT_LOGIN_PAGE, false));
        }

        // 校验是否用户密码是否合法.
        Authenticate authenticate = new Authenticate();
        try {
            // TODO:密码需要base64编码
            // sun.misc.BASE64Decoder
            remoteUser = authenticate.login(username, password, request.getRemoteAddr());
            session.setAttribute(RemoteUserRequestWrapper.USER_SESSION_KEY, remoteUser);
            
            
        } catch (ObjectNotExistsException e) {
            // 用户不存在
            request.setAttribute(RequestProcessor.MESSAGE_KEY, "用户不存在.");
            return (new ActionForward(RequestProcessor.DEFAULT_LOGIN_PAGE, false));
        } catch (AuthenticateException e) {
            // 密码错误
            request.setAttribute(RequestProcessor.MESSAGE_KEY, "密码错误.");
            return (new ActionForward(RequestProcessor.DEFAULT_LOGIN_PAGE, false));
        }

        if (!GenericValidator.isBlankOrNull(redirect)) {
            return (new ActionForward(redirect, true));
        }
        return (new ActionForward(RequestProcessor.DEFAULT_REDIRECT_PAGE, true));
    }

    /**
     * 输入校验.
     * 如果校验出错时想request中加入消息.
     *
     * @param request
     * @return boolean
     */
    protected boolean validate(HttpServletRequest request) {
        String username = request.getParameter("name");
        String password = request.getParameter("password");

        if (GenericValidator.isBlankOrNull(username)) {
            request.setAttribute(RequestProcessor.MESSAGE_KEY, "请输入用户名.");
            return false;
        }

        if (GenericValidator.isBlankOrNull(password)) {
            request.setAttribute(RequestProcessor.MESSAGE_KEY, "请输入密码.");
            return false;
        }

        return true;
    }

}
